<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.monitoringQuantityTypeName" placeholder="监测量类型名称" clearable
            @clear="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 监测量类型表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon>
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-table v-loading="loading" :data="tableData" border align="center" class="monitoring-table mt-2">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="monitoringQuantityTypeName" label="监测量类型名称" align="center" />
        <el-table-column prop="description" label="描述" align="center" />
        <el-table-column prop="filed" label="字段标识" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="valueType" label="值类型" align="center">
          <template #default="{ row }">
            {{ valueTypeMap[row.valueType] || row.valueType }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row.monitoringQuantityTypeId)"
              style="color: #F56C6C">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="mt-2" v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="`${isEditMode ? '编辑' : '新增'}监测量类型`" width="600px"
      @closed="handleDialogClosed">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="监测量类型名称" prop="monitoringQuantityTypeName">
          <el-input v-model="formData.monitoringQuantityTypeName" placeholder="请输入监测量类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="字段标识" prop="filed">
          <el-input v-model="formData.filed" placeholder="请输入字段标识" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="值类型" prop="valueType">
          <el-select v-model="formData.valueType" placeholder="请选择值类型" style="width: 100%">
            <el-option v-for="(label, value) in valueTypeMap" :key="value" :label="label" :value="parseInt(value)" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import * as api from '@/api/park/monitor/type'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  monitoringQuantityTypeName: undefined
})

// 搜索表单
const searchForm = reactive({
  monitoringQuantityTypeName: undefined
})

// 表单数据
const formData = reactive({
  monitoringQuantityTypeId: undefined,
  monitoringQuantityTypeName: '',
  description: '',
  filed: '',
  unit: '',
  valueType: undefined
})

// 表单验证规则
const rules = reactive({
  monitoringQuantityTypeName: [
    { required: true, message: '监测量类型名称不能为空', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '描述不能为空', trigger: 'blur' }
  ],
  filed: [
    { required: true, message: '字段标识不能为空', trigger: 'blur' }
  ],
  valueType: [
    { required: true, message: '请选择值类型', trigger: 'change' }
  ]
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 值类型映射
const valueTypeMap = ref({
  0: '数值型',
  1: '布尔型',
  2: '字符串'
})

// 对话框控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)

// 初始化数据
onMounted(() => {
  getList()
})

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const res = await api.getMonitoringQuantityTypeList(queryParams)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    ...searchForm
  })
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    monitoringQuantityTypeName: undefined
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 显示新增对话框
const showCreateDialog = () => {
  isEditMode.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await api.getMonitoringQuantityTypeDetail(row.monitoringQuantityTypeId)
    Object.assign(formData, res.data)
    isEditMode.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 对话框关闭
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    monitoringQuantityTypeId: undefined,
    monitoringQuantityTypeName: '',
    description: '',
    filed: '',
    unit: '',
    valueType: undefined
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (isEditMode.value) {
        await api.updateMonitoringQuantityType(formData)
        ElMessage.success('修改成功')
      } else {
        await api.addMonitoringQuantityType(formData)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败')
    }
  })
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await api.deleteMonitoringQuantityType(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}
</script>

<style scoped>
.monitoring-table {
  width: 100%;
}

.text-right {
  text-align: right;
}

.mt-1 {
  margin-top: 10px;
}

.mt-2 {
  margin-top: 20px;
}
</style>